<template>
  <el-dialog class="public-dialog" :title="title" width="560" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div>
      <XForm ref="form" :formData="model" :fieldList="fieldList" :options="formOptions" :rules="rules" :originOption="{ ...option, ...originOption }" />
    </div>
    <div class="text-[14px] leading-[20px]">
      <p class="text-[#6C7283] mt-[8px]">说明：如果不选择上级退款原因，则系统自动添加为一级退款原因</p>
    </div>
    <template #footer>
      <div class="flex items-center justify-end py-[10px]">
        <el-button :disabled="loading" @click="handleClose(false)"> 取消 </el-button>
        <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import XForm from "@/components/XForm/index.vue"
import { apiGetPlatform } from "@/api/public"
import { apiCreateReason, getReasonOptions, updateRefundReason } from "../../../api/index"
import { watch } from "vue"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  rows: { type: Object, default: () => ({}) },
  edit: { type: Boolean, default: false },

  option: { type: Object, default: () => ({}) },
})

const title = computed(() => (props.edit ? "编辑退款原因" : "新增退款原因"))

const emit = defineEmits(["update:modelValue", "refresh"])

const model = ref({
  is_enable: 0,
})

const handleChangePlatform = async (e) => {
  if (e) {
    const { data } = await getReasonOptions({ parent_id: "0", platform_id: e })
    originOption.value.parent_id = data.map((n) => ({ label: n.reason, value: n.id }))
    model.value.platform = props.option?.platform.find((v) => v.value == e)?.label
  }
}
const originOption = ref({})

const form = ref()
const loading = ref(false)
const fieldList = ref([
  {
    field: "platform_id",
    type: "select",
    label: "平台",
    originField: "platform",
    itemProps: {
      onChange: handleChangePlatform,
    },
  },
  {
    field: "parent_id",
    type: "select",
    label: "上级退款原因",
    originField: "parent_id",
    disabled: !!props.edit,
  },
  { field: "reason", label: "退款原因" },
  {
    field: "is_enable",
    label: "状态",
    type: "switch",
    itemProps: {
      inlinePrompt: true,
      activeText: "启用",
      inactiveText: "禁用",
      activeValue: 1,
      inactiveValue: 0,
    },
  },
])

const rules = reactive({
  platform_id: [{ required: true, message: "请输入平台", trigger: "blur" }],
  reason: [{ required: true, message: "请输入退款原因", trigger: "blur" }],
})

onMounted(() => {})

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let rows = props.rows
      model.value = {
        ...rows,
        parent_id: rows.parent_id || "",
      }

      console.log(model.value)
      // 新增
      if (!rows.id) {
        model.value.platform_id = rows.platform_id
        fieldList.value.forEach((item) => {
          if (["parent_id", "platform_id"].includes(item.field)) item.disabled = false
        })
      } else {
        // 编辑
        fieldList.value.forEach((item) => {
          if (["parent_id", "platform_id"].includes(item.field)) item.disabled = true
        })
      }

      handleChangePlatform(model.value.platform_id)
    }
  }
)

const handleSave = async () => {
  try {
    loading.value = true
    await form.value.submit()
    const api = {
      edit: updateRefundReason,
      add: apiCreateReason,
    }
    await api[props.edit ? "edit" : "add"]({
      ...model.value,
      parent_id: model.value?.parent_id || 0,
    })

    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = (refresh) => {
  emit("update:modelValue", false)
  form.value.resetForm()
  if (refresh) emit("refresh")
}

const formOptions = { labelWidth: "100px" }
</script>
